/**
 * Created by Skye on 2018/3/29.
 */
import React, { Component } from 'react';
import { Button } from 'antd';
import axios from '../../../utils/axios';
import AddDepartment from './addDepartment';

function arrayToTree(data) {
  let resData = data;
  let tree = [];
  for (let i = 0; i < resData.length; i++) {
    if (!resData[i].parentDepartmentCode) {
      resData[i].label = resData[i].departmentName;
      resData[i].value = resData[i].departmentCode;
      resData[i].children = []
      tree.push(resData[i]);
      resData.splice(i, 1);
      i--
    }
  }
  getChildren(tree);
  function getChildren(arr) {
    if (resData.length > 0) {
      for(let i = 0; i < arr.length; i++) {
        for (let j = 0; j < resData.length; j++) {
          if (arr[i].departmentCode === resData[j].parentDepartmentCode) {
            resData[j].label = resData[j].departmentName;
            resData[j].value = resData[j].departmentCode;
            resData[j].children = [];
            arr[i].children.push(resData[j]);
            resData.splice(j,1);
            j--
          }
        }
        getChildren(arr[i].children)
      }
    }
  }
  return tree;
}

export default class DepartmentManager extends Component {

  constructor(props) {
    super(props)
    this.state = {
      showModal: false,
      departmentList: [],
      departmentTree: []
    }
  }

  componentDidMount() {
    this.getDepartmentList()
  }

  getDepartmentList = async () => {
    const params = {
      recordStatus: 1
    }
    const response = await axios.post('/api/rbac/mgmt/list-department', params);
    const { success, data } = response.data;
    if (success) {
      this.setState({
        departmentList: data,
        departmentTree: arrayToTree(data)
      })
    }
    console.log('state', this.state);
  }

  addSuccess() {
    console.log('添加成功')
  }

  showModal = () => {
    this.setState({
      showModal: true
    })
  }

  closeModal = (val) => {
    if (val) {
      this.getDepartmentList();
    }
    this.setState({
      showModal: false
    })
  }

  render() {
    return (
        <div>
          <Button type="primary" icon="plus" onClick={this.showModal}>新建</Button>
          <AddDepartment  visible={this.state.showModal} departmentList={this.state.departmentTree} closeModal={this.closeModal} addSuccess={this.addSuccess} />
        </div>
    )
  }
}